<!--相关方检查 relatedPartyInspection-->
<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="二级集团：">
                        <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="单位名称：" prop="order">
                        <company-select v-model="dataToQuery.companyName" style="width:100%" />
                        <!-- <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgname='setQueryOrgName' :orgTree="true"
                                      :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom> -->
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label="检查时间：" prop="content">
                        <DatePicker class="query-form-el" v-model="dataToQuery.inspectionRange" format="yyyy-MM-dd"
                                    type="daterange" placement="bottom-end" placeholder="请选择检查时间范围"
                                    @on-change="(date) => onSelectFieldQueryDateRange(date, 'inspectionDate')"></DatePicker>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label='相关方名称：'>
                        <Input class='' type='text' v-model='dataToQuery.contractorName'></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="填报时间：" prop="content">
                        <DatePicker class="query-form-el" v-model="dataToQuery.createRange" format="yyyy-MM-dd"
                                    type="daterange" placement="bottom-start" placeholder="请选择填报时间范围"
                                    @on-change="(date) => onSelectFieldQueryDateRange(date, 'createDate')"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="是否整改完成：">
                        <Select class="query-form-el" v-model="dataToQuery.ifRectify" clearable>
                            <Option value="1">是</Option>
                            <Option value="0">否</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <Button type="primary" class="ivu-btn-add" :loading="buttonLoading" icon="md-cloud-download"
                            @click="exportFormSubmit">导出
                    </Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
        @on-sort-change="sortChange" show-summary :summary-method="(data) => this.gAmountTo(data,['inspectionNum','rectificationNum'])"  
        :loading='pageStatus.loading' border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange"
                      @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
                      show-elevator/>
            </Col>
        </Row>
        <Modal :title="mode === 'view'?'相关方检查详情':'相关方检查'" :transfer=false :mask-closable="false" v-model="dialogShow"
               v-if="dataToView && dialogShow" :width=800 :styles="{height:'748px'}" class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
                          :model="dataToView" :rules="mode === 'view'?{}:ruleCustom"
                          :label-width="mode === 'view'?170:null"
                          :label-position="mode === 'view'?'right':'top'">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span='11'>
                                <FormItem label='相关方作业事项：' prop="workingMatters">
                                    <div v-if="mode === 'view'">{{ dataToView.workingMatters }}</div>
                                    <Input v-else class='' placeholder="请填写相关方名称" type='text' v-model='dataToView.workingMatters'
                                           readonly @on-focus="modelSearch=true" suffix="ios-search"></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='相关方名称：' prop='contractorName'>
                                    <div v-if="mode === 'view'">{{ dataToView.contractorName }}</div>
                                    <Input v-else class='' placeholder="请填写相关方名称" type='text' readonly v-model='dataToView.contractorName'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='检查内容：' prop='inspectionContent'>
                                    <div v-if="mode === 'view'">{{dataToView.inspectionContent}}</div>
                                    <Input v-else class='' type='text' v-model='dataToView.inspectionContent'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='检查时间：' prop='inspectionDate'>
                                    <div v-if="mode === 'view'">{{renderViewDate(dataToView.inspectionDate)}}</div>
                                    <DatePicker v-else type="date" placeholder="请选择检查日期" style="width: 100%" v-model='dataToView.inspectionDate'></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='检查问题：' prop='inspectionNum'>
                                    <div v-if="mode === 'view'">{{dataToView.inspectionNum}}</div>
                                    <InputNumber v-else class='w' :min="0" placeholder="请填写检查问题数量" type='text' v-model='dataToView.inspectionNum'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='检查人员：' prop='inspectionStaff'>
                                    <div v-if="mode === 'view'">{{dataToView.inspectionStaff}}</div>
                                    <Input v-else class='' type='text' v-model='dataToView.inspectionStaff'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='检查过程描述：' prop='inspectionDescription'>
                                    <div v-if="mode === 'view'">{{dataToView.inspectionDescription}}</div>
                                    <Input v-else class='' type='text' v-model='dataToView.inspectionDescription'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='整改数量：' prop='rectificationNum'>
                                    <div v-if="mode === 'view'">{{dataToView.rectificationNum}}</div>
                                    <InputNumber v-else class='w' :min="0" placeholder="请填写整改数量" type='text' v-model='dataToView.rectificationNum'></InputNumber>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='整改完成时间：' prop='rectificationDate'>
                                    <div v-if="mode === 'view'">{{renderViewDate(dataToView.rectificationDate)}}</div>
                                    <DatePicker v-else type="date" placeholder="请选择整改完成时间" style="width: 100%" v-model='dataToView.rectificationDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='整改过程描述：' prop='rectificationDescription'>
                                    <div v-if="mode === 'view'">{{dataToView.rectificationDescription}}</div>
                                    <Input v-else class='' type='text' v-model='dataToView.rectificationDescription'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="上传附件：">
                                    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadFile(dataToView.id,item)">{{ item.fileName }}</a>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="上传附件：">
                                    <div>
                                        <Upload ref="upload"
                                                :before-upload="beforeUpload"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 20px">
                                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadFile(dataToView.id,item)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                                style="margin-left: 5px;margin-bottom: 3px"/>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='registrant'>
                                    <div v-if="mode === 'view'">{{dataToView.createUserName}}</div>
                                    <Input v-if="mode === 'add'" type='text' v-model='dataToView.registrant' readonly></Input>
                                    <Input v-if="mode === 'edit'" type='text' v-model='dataToView.createUserName' readonly></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='registTime'>
                                    <div v-if="mode === 'view'">{{renderViewDate(dataToView.createDate)}}</div>
                                    <DatePicker v-if="mode === 'add'" type="date" placeholder="请选择日期" class="w" v-model='dataToView.registTime' readonly></DatePicker>
                                    <DatePicker v-if="mode === 'edit'" type="date" placeholder="请选择日期" class="w" v-model='dataToView.createDate' readonly></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人电话：' prop='createMobile'>
                                    <div v-if="mode === 'view'">{{dataToView.createMobile}}</div>
                                    <Input v-if="mode === 'add'" type='text' v-model='dataToView.createMobile'></Input>
                                    <Input v-if="mode === 'edit'" type='text' v-model='dataToView.createMobile'
                                           :readonly="this.currentUser.userId === dataToView.createUserId ? false : 'readonly'"></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                            </Col>
                        </Row>
                    </Form>
                    <Modal title="相关方作业信息" :transfer=false footer-hide v-model="modelSearch" :width=900>
                        <working-related-parties v-if="modelSearch" v-show="modelSearch" :modelSearch="modelSearch"
                                                 @getSelectModelData='danxuan'
                                                 :companyId="currentUser.companyId"></working-related-parties>
                        <div slot="footer">
                            <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
                        </div>
                    </Modal>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save'
                        @click="submit('dialogForm')">确定
                </Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    import {sessionStorage} from '@/common/cacheUtils.js'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import workingRelatedParties from './workingRelatedParties.vue'

    export default {
        components: {cascaderDom, workingRelatedParties},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                  {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRenderSum},
                    {key: 'companyName', title: '所属单位', align: 'center', width: 200,tooltip: true},
                  {minWidth: 150, title: '作业事项', align: 'center', key: 'workingMatters', tooltip: true},
                  {key: 'contractorName', title: '相关方名称', align: 'center', width: 200},
                  {key: 'inspectionContent', title: '检查内容', align: 'center', width: 200, tooltip: true},
                  {key: 'inspectionDate', title: '检查时间', sortable: "custom",align: 'center', width: 150, render: this.renderCellDate},
                  {key: 'inspectionNum', title: '检查问题', align: 'center', width: 120, tooltip: true},
                  {key: 'inspectionStaff', title: '检查人员', align: 'center', width: 150, tooltip: true},
                  {key: 'inspectionDescription', title: '检查过程描述', align: 'center', width: 200, tooltip: true},
                  {key: 'rectificationNum', title: '整改数量', align: 'center', width: 120},
                  {key: 'rectificationDescription', title: '整改过程描述', align: 'center', width: 200, tooltip: true},
                  {key: 'rectificationDate', title: '整改完成时间', sortable: "custom",align: 'center', width: 150, render: this.renderCellDate},
                    {key: 'createDate', title: '填报时间', sortable: "custom",align: 'left', width: 120, render: this.renderCellDate},
                    this.getActionColumns((params) => {return params.row.id === '-1';}),
                ],
                ruleCustom: {
                    contractorName: [{required: true, message: '请填写相关方名称', trigger: 'change'}],
                    inspectionContent: [{required: true, message: '请填写检查内容', trigger: 'change'}],
                    inspectionDate: [{required: true, message: '请填写检查时间', trigger: 'change', type: 'date'}],
                    createMobile: [{
                        pattern: /^((0\d{2,3}-\d{7,8})|(1[123456789]\d{9}))$/,
                        required: true,
                        message: '请填写填报人电话',
                        trigger: 'change'
                    }],
                },
                tableHeight: 10,
                uploadList: [],
                queryUrl: Api.queryInspection,
                exportUrl: Api.exportInspection,
                deleteUrl: Api.deleteInspection,
                updateUrl: Api.updateInspection,
                saveUrl: Api.saveInspection,
                buttonLoading: false,
                modelSearch:false
            }
        },
        async mounted() {
            this.setTableHeight(193);
            this.dataToQuery.rptType = this.$route.query.id
            this.query();
        },
        methods: {
            ...pageCommonFunction,

            deleteData(params) {
                this.deleteDateAjax(params);
            },
            setOrgId1(data) {
                this.dataToQuery.traOrgId = data[data.length - 1];
            },
            danxuan(row, index) {
              this.modelSearch = false;
              // this.InputData.contractorId = row.contractorId
              this.dataToView.contractorName = row.relatedPartiesName//相关方名称
              this.dataToView.workingMatters = row.workingMatters//作业事项
              this.dataToView.workingRelatedId = row.id//相关方作业id
            },
          query() {
            this.dataToQuery.orgId = this.currentUser.companyId
            this.queryAjax();
          },
          queryAjax() {
            this.pageStatus.loading = true
            let data = {
              startPage: this.pagedata.currentPage,
              size: this.pagedata.pageSize,
              conditions: this.dataToQuery
            };

            this.$http.post(this.queryUrl, data).then((res) => {
              if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
              }
              this.dataTable = res.data.data.data;
              this.dataTable.unshift(res.data.data.totalMap)
              this.pagedata.total = res.data.data.totalSize;
              this.pageStatus.loading = false
            }).catch(e => {
              this.$Message.error("数据获取失败")
              this.pageStatus.loading = false
            })
          },
          submit(name) {
            if (this.dataToView.inspectionNum == '') this.dataToView.inspectionNum = 0;
            if (this.dataToView.rectificationNum == '') this.dataToView.rectificationNum = 0;
            this.submitAjax(name);
          },
          addInfo() {
            this.uploadList = [];
            this.dataToView = {};
            this.dataToView = (this.createEmptyDataToAdd instanceof Function) ? this.createEmptyDataToAdd() : {};
            this.dataToView.id = this.get_uuid();
                this.dataToView.companyId = this.currentUser.companyId;
                this.dataToView.companyName = this.currentUser.companyName;
                this.dataToView.belongOrgId = this.currentUser.twoLevelOrgId;
                this.dataToView.belongOrgName = this.currentUser.twoLevelOrgName;
                this.dataToView.registrant = this.currentUser.userName;
                this.dataToView.registrantPhone = this.currentUser.mobileNumber;
                this.dataToView.registTime = new Date();
                this.mode = 'add'
                this.dialogShow = true;
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 88;
                } else {
                    this.tableHeight = this.tableHeight - 88;
                }
            },
            exportFormSubmit() {
                this.buttonLoading = true
                let orgId = sessionStorage('userId').getObject('userId').companyId
                let data = {
                    orgId: orgId,
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
                this.$http.get(Api.exportInspection, {
                    params: data,
                    responseType: 'blob' //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = "相关方检查表(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                    this.buttonLoading = false
                })
            },
            beforeUpload(file) {
                let formData = new FormData();
                formData.append("files", file); // 文件对象
                let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
                this.$http.post(url, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.info("文件上传成功")
                        this.getFiles();
                    }
                });
                return false
            },
            getFiles() {
                let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
                this.$http.get(url).then((res) => {
                    if (res.data.result == "success") {
                        this.uploadList = res.data.data
                    }
                })
            },
            downloadFile(guideId, file) {
                let url = this.fileUrl + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            remove1(id) {
                let url = this.fileUrl + '/file/' + id;
                this.$http.delete(url).then((res) => {
                    this.getFiles()
                })
            },
            createEmptyDataToAdd() {
                return {
                    fileId: this.get_uuid(),
                    createMobile: sessionStorage('userId').getObject('userId').mobileNumber,
                    inspectionNum: 1,
                    rectificationNum: 1,
                }
            },
            async afterDataToViewInit() {
                await this.getFiles('fileId');
            }
        },
        watch: {},

    }
</script>

<style lang='css' scoped>
    .rpt-form {
    }

    /deep/ .rpt-form .query-form-el {
        width: 100%;
    }
</style>
